export default {
	namespaced:true,
	
	state:()=>({
		cart:JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	
	getters:{
		// 商品的总数量
		total(state){
			let c=0
			state.cart.forEach(goods =>  c+= goods.goods_count)
			return c
		},
		// 选中商品的数量
		checkedConut(state){
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=> total += item.goods_count,0)
		},
		// 获取选中商品的总价格
		checkedTotalNums(state){
			return state.cart.filter(x => x.goods_state).reduce((total,item) => total += item.goods_price*item.goods_count,0).toFixed(2)
		}
	},
	
	mutations:{
		// 添加商品
		addToCart(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(!findResult){
				state.cart.push(goods)
			}else{
				findResult.goods_count++
			}
			this.commit('m_cart/saveToStorage')
		},
		// 更新商品的状态
		updateGoodsState(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(findResult){
				findResult.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		// 更新商品的选中数量 
		updateGoodsCount(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(findResult){
				findResult.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		// 全选商品
		updataAllCountState(state,stating){
			state.cart.forEach(x => x.goods_state = stating)
			this.commit('m_cart/saveToStorage')
		},
		// 删除商品
		removeGoods(state,goods_id){
			
			state.cart = state.cart.filter(x =>x.goods_id !== goods_id)
			this.commit('m_cart/saveToStorage')
			
		},
		// 永久保存数据
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		}
	}
	
}